package gov.pbc.nn.kjgl.jfcr.ureportview;

import gov.pbc.nn.core.dao.AbstractJdbcDao;
import gov.pbc.nn.core.utils.FileUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.FileAttribute;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.imageio.stream.FileImageOutputStream;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import org.apache.tools.ant.types.selectors.SizeSelector.ByteUnits;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;

import com.bstek.ureport.datasource.ReportDataProvider;

@Component
public class JfcrReportDataProvider extends AbstractJdbcDao implements ReportDataProvider<JfImage> {

	@Override
	public List<JfImage> provide(String datasourceName, Map<String, Object> parameters) {
		String id = parameters.get("id").toString();
		if (id != null) {
			return getComputerRoomApplyEntry(id);
		}
		return null;
	}

	public List<JfImage> getComputerRoomApplyEntry(String id) {

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("id", id);
		String Sql = "select * from T_COMPUTER_ROOM_APPLY_ENTRY where ID_=?";
		return this.getJdbcTemplate().query(Sql, new Object[] { id }, new RowMapper<JfImage>() {
			@Override
			public JfImage mapRow(ResultSet rs, int rowNum) throws SQLException {
				JfImage crap = new JfImage();
				try {
					crap.setImagepath(returnImagePath(rs.getBytes("SIGN_IMG_")));
				} catch (IOException e) {
					e.printStackTrace();
				}
				return crap;
			}
		});
	}

	public String returnImagePath(byte[] b) throws IOException {
		if (b != null) {
			UUID uuid = UUID.randomUUID();
			String basePath = "c:/temp/";
			String attrPath = uuid + ".jpg";
			String path = basePath + attrPath;
			File f = new File(basePath);
			if (f.exists()) {
				FileUtils.deleteDirectory(f);
			}
			try {
				if (!f.exists()) {
					f.mkdirs();
				}
				File file = new File(basePath, attrPath);
				if (!file.exists()) {
					file.createNewFile();
				}
				FileOutputStream imageOutput = new FileOutputStream(file);
				String tempb = new String(b);
				String substringAfter = StringUtils.substringAfter(tempb, "data:image/jpeg;base64,");
				byte[] decodeBase64 = Base64.decodeBase64(substringAfter);
				FileCopyUtils.copy(decodeBase64, imageOutput);
				// imageOutput.write(b, 0, b.length);
				// imageOutput.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return "file:" + path;
		}else{
			return null;
		}
	}
}
